package com.geek.javaCource.demo.consumer.service;

import com.geek.javaCource.demo.provider.entity.Trace;
import com.geek.javaCource.demo.provider.service.AccountService;
import com.geek.javaCource.demo.provider.service.TraceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.stereotype.Service;

/**
 * Create by chenhd on 2021/10/10.
 */
@Service
public class AccountServiceImpl implements AccountService {

    @DubboReference
    TraceService traceService;

    /**
     * 客户端业务入口，因为没有部署多个provider，作为测试简单往一个提供方请求2次
     */
    @HmilyTCC(confirmMethod = "confirmMethod", cancelMethod = "cancelMethod")
    public void trace(Trace trace1, Trace trace2) {
        boolean result1 = traceService.tryFrozen(trace1);
        boolean result2 = traceService.tryFrozen(trace2);
        if (!result1 || !result2) {
            throw new RuntimeException("consumer try fail");
        }
    }


    public boolean confirmMethod(Trace trace1, Trace trace2) {
        System.out.println("consumer confirm");
        //去第一个库，把用户1的冻结账户清空，并把用户2转账的资金给用户1
        traceService.commitTrace(trace2, trace1);
        //去第二个库，把用户2的冻结账户清空，并把用户1转账的资金给用户2
        traceService.commitTrace(trace1, trace2);
        return true;
    }

    public boolean cancelMethod(Trace trace1, Trace trace2) {
        System.out.println("consumer cancel");
        traceService.cancelTrace(trace1);
        traceService.cancelTrace(trace2);
        return true;
    }
}
